<template>
  <div class="login-container">
    <div class="login-form">
      <div style="margin-top: 10px">
        <div class="login-title">{{ gmconfig.title }}</div>
        <a-form ref="myform" :model="user">
          <a-form-item
            hide-label
            field="account"
            :rules="[{ required: true, message: '必须输入用户名/手机号/电子邮件' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input
              v-model="user.account"
              placeholder="请输入用户名/手机号/电子邮件"
              allow-clear
              size="large"
            >
              <template #prefix>
                <icon-mobile />
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
            hide-label
            field="password"
            :rules="[{ required: true, message: '必须输入密码' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input-password
              v-model="user.password"
              placeholder="请输入密码"
              allow-clear
              size="large"
            >
              <template #prefix>
                <icon-lock />
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item hide-label>
            <a-button type="primary" long :loading="data.loading" @click="onLogin">
              {{ data.loginButton }}
            </a-button>
          </a-form-item>
          <a-form-item hide-label>
            <div class="login-join">
              <a-button type="text" @click="onJoin">新用户注册</a-button>
              <a-button type="text" @click="onCaptcha">忘记密码</a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>

      <!--底部微信登录和版本信息-->
      <div style="text-align: center">
        <div style="padding-top: 10px">
          <a-button type="text" @click="onWeixin">
            <template #icon><icon-wechat size="40" /></template>
          </a-button>
        </div>
        <div style="padding-top: 10px; text-align: center">
          {{ data.message }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { useCommonStore } from '@/stores/common'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import voca from 'voca'
import { sm2 } from 'sm-crypto'
import gmconfig from '@/api/gmconfig.json'
import gmapi from '@/api/gmapi'

const store = useCommonStore()
const route = useRoute()
const router = useRouter()

const mode = {
  C1C3C2: 1,
  C1C2C3: 0
}

const data = reactive({
  loginButton: '下载密钥中', // 密码登录按钮文字
  loading: true, // 密码登录按钮loading状态
  publicKey: '', // 加密公钥
  message: 'client：1.0， service：1.0' // 底部版本信息显示内容
})
const user = reactive({
  account: '',
  password: '',
  captcha: ''
})

let redirect = '' // 登陆之前的url

// 页面组件
const myform = ref()

onMounted(() => {
  store.clearUser()
  if (!voca.isBlank(route.query.redirect)) {
    redirect = decodeURIComponent(route.query.redirect)
    console.log('传入的登录前url', redirect)
  } else {
    redirect = gmconfig.urlHome
  }
  gmapi
    .publickey()
    .then((res) => {
      if (res.code == 0) {
        // 成功
        data.loginButton = '登录'
        data.loading = false
        data.publicKey = res.message
      } else {
        Message.error(res.message)
      }
    })
    .catch((err) => {
      console.log(err)
      Message.error('无法下载密钥')
    })
})

const onLogin = () => {
  console.log('myform', myform)
  myform.value
    ?.validate()
    .then((error) => {
      if (error) {
        console.log('validate 不通过')
      } else {
        console.log('validate通过')
        loginByPassword()
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}
const loginByPassword = () => {
  // 国密算法 sm-crypto 库, 使用 C1C3C2 模式，与后端对应
  const encpass = sm2.doEncrypt(user.password, data.publicKey, mode.C1C3C2)

  // 注意 gm-crypto 或 sm-crypto 密文有 04 前缀，要加上与后端对应
  const params = {
    account: user.account,
    password: '04' + encpass
  }
  gmapi
    .login(params)
    .then((res) => {
      if (res.code == 0) {
        // 登录成功, 返回的 data 属性为用户实体
        store.setUser(res.data)
        // 返回登录前的页面或首页
        router.replace(redirect)
      } else {
        Message.error(res.message)
      }
    })
    .catch((err) => {
      console.log('login error:', err)
      Message.error('登录接口发生错误')
    })
}
const onWeixin = () => {
  Message.warning('开发中')
}
const onJoin = () => {
  Message.warning('开发中')
}
const onCaptcha = () => {
  Message.warning('开发中')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/bg_img.webp');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;
}
.login-form {
  width: 400px;
  height: 430px;
  border: 1px solid #c9cdd4;
  border-radius: 10px;
  padding: 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: white;
}
.login-title {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 30px;
  text-align: center;
}
.login-join {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
